﻿Public Class ProjectOutlineForm


    Private _imageControlList As IList(Of ImgControl)

    Private _p As ProjectOutlineDataItem
    Private _bLoad As Boolean = False

    Public ReadOnly Property PodItem() As ProjectOutlineDataItem
        Get
            Return _p
        End Get
    End Property

    Private Sub ProjectOutlineForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        _imageControlList = New List(Of ImgControl)

        Init()

        ''Log.log(tbccLogOperateType.View, "查看工程图")

        'AddHandler RTDReader.Instance.NewDataEvent, AddressOf OnNewData
        ' StartNewdataRefresh()
        _bLoad = True
        RefreshControls()

        Me.Visible = False
        '_bLoad = True
    End Sub


    Public Sub StartNewdataRefresh()
        _p = New ProjectOutlineDataItem(MainForm.MasterNetID)
        AddHandler _p.NewDataEvent, AddressOf NewData
        AddHandler _p.PlayAlarmSoundEvent, AddressOf NoticeAlarmSound
    End Sub

  

    ''' <summary>
    ''' 初始化
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Init()
        Dim pi As ProjectItem
        pi = MainForm.pi

        Me.TabControlImages.TabPages.Clear()
        For Each pii As ProjectImageItem In pi.imageList
            Dim page As New TabPage()
            page.Text = pii.imageName
            'page.BackColor = Color.White

            Dim pic As New PictureBox

            'pic.BackColor = Color.Transparent

            If System.IO.File.Exists(pii.imagePath) Then
                pic.Image = Image.FromFile(pii.imagePath)
            End If

            Dim lbl As New Label
            lbl.BackColor = Color.White
            lbl.Location = New Point(10, 10)
            lbl.ForeColor = Color.Red
            lbl.Font = New Font("宋体", 20)
            lbl.AutoSize = True
            lbl.Text = "提示:读取数据失败"
            lbl.Visible = False
            page.Controls.Add(lbl)

            pic.Dock = DockStyle.Fill
            pic.SizeMode = PictureBoxSizeMode.StretchImage
            page.Controls.Add(pic)


            Me.TabControlImages.TabPages.Add(page)

            LoadImgControls(pii, page)

            pic.SendToBack()
        Next
    End Sub

    ''' <summary>
    ''' 加载控件
    ''' </summary>
    ''' <param name="pii"></param>
    ''' <param name="parentCtl"></param>
    ''' <remarks></remarks>
    Private Sub LoadImgControls(ByVal pii As ProjectImageItem, ByVal parentCtl As Control)
        For Each item As ImgControlItem In ImgControlService.GetControls(pii.projectID, pii.ImageID)
            Dim ctl As Control
            ctl = CreateImageControl(item, parentCtl)
            If ctl IsNot Nothing Then
                _imageControlList.Add(ctl)
                parentCtl.Controls.Add(ctl)
                'ctl.BringToFront()
            End If
        Next
    End Sub

    Private Function CreateImageControl(ByVal item As ImgControlItem, ByVal parentCtl As Control) As Control
        Dim ctl As Control = New ImgControl

        If ctl Is Nothing Then
            Return Nothing
        End If

        CType(ctl, ImgControl).ici = item
        CType(ctl, ImgControl).IsDesign = False

        Dim iWidth As Integer = parentCtl.Width
        Dim iHeight As Integer = parentCtl.Height

        ctl.Location = New Point((item.cLeft / 1024.0) * iWidth, (item.cTop / 768.0) * iHeight)
        ctl.Size = New Size((item.cWidth / 1024.0) * iWidth, (item.cHeight / 768.0) * iHeight)

        AddHandler CType(ctl, ImgControl).ShowDetailsEvent, AddressOf OnShowDetails

        Return ctl
    End Function

    ''' <summary>
    ''' 双击显示对应明细数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub OnShowDetails(ByVal sender As Object, ByVal e As EventArgs)
        'Dim frm As Form = Nothing

        'Select Case sender.ctrlName
        '    Case "CompressorGroup"
        '        frm = New RTD_CompresserForm

        '    Case "Condenser"
        '        frm = New RTD_CondenserForm

        '    Case "Circuit"
        '        frm = New RTD_CircuitForm

        'End Select

        'If frm IsNot Nothing Then
        '    CType(frm, IRTDForm).SelectItem(sender.dataID)
        '    frm.ShowDialog()
        'End If

    End Sub

    ''' <summary>
    ''' 接收到实时数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub NewData(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Try
            CType(sender, ProjectOutlineDataItem)._RefreshProcessing = True '正在刷新工程数据主窗口

            If e Is Nothing Then
                '读取数据失败
                'todo:提示读取数据失败
                SetReadErrorLableVisible(True)
                'System.IO.File.AppendAllText("./ConnectInfo.Log", _
                '                            String.Format("{0} =====> 连接类型:{1}, {2}" & vbCrLf, Now, MainForm.pi.connectType, "提示读取数据失败"), _
                '                            System.Text.Encoding.UTF8)
            Else
                SetReadErrorLableVisible(False)
                '刷新所有控件值
                refreshControlval(sender)
            End If

            CType(sender, ProjectOutlineDataItem)._RefreshProcessing = False  '刷新工程数据主窗口结束
        Catch ex As Exception
            Debug.Print("newdata exception\n")
        End Try
    End Sub

    Private Sub NoticeAlarmSound(ByVal sender As Object, ByVal e As System.EventArgs)
        PlayAlarmSound()
    End Sub

    ''' <summary>
    ''' 播放报警声音
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PlayAlarmSound()
        Dim fileName As String
        fileName = g_AlarmSoundFile
        If fileName = "" OrElse Not System.IO.File.Exists(fileName) Then
            Exit Sub
        End If
        My.Computer.Audio.Play(fileName, AudioPlayMode.Background)
    End Sub


    Private Delegate Sub refreshControlvalhandler(ByVal sender As System.Object)

    Private Sub refreshControlval(ByVal sender As System.Object)
        If Me.InvokeRequired Then
            Dim d As New refreshControlvalhandler(AddressOf _refreshControlval)
            Me.Invoke(d, New Object() {sender})
        Else
            _refreshControlval(sender)
        End If
    End Sub

    Private Sub _refreshControlval(ByVal sender As System.Object)
        Dim v As ProjectOutlineDataItem
        v = CType(sender, ProjectOutlineDataItem)
        '刷新所有控件的值
        For Each item As ProjectOutlineDataItem.OutlineItem In v.outlineItemList '每个网络的数据
            'Debug.WriteLine("Item.netID=" & item.netID)
            For Each ctl As ImgControl In Me._imageControlList
                'Debug.WriteLine("ctl.netID=" & ctl.netID)
                If ctl.ici.Netid = item.netID Then
                    If ctl.ici.DataType = 1 OrElse ctl.ici.DataType = 2 Then '温度或湿度数据
                        ctl.value = item.GetAiValue(ctl.ici.PortNo)
                    ElseIf ctl.ici.DataType = 3 Then '报警数据
                        If ctl.ici.PortNo = 1 Then '冷库报警  （此处使用报警数据中不用的portno表示不同的报警类型）
                            ctl.value = item.GetRefAlarmStatus(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 2 Then '声光报警功能
                            ctl.value = item.GetSoundAlarmStatus(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 3 Then '缺项报警功能
                            ctl.value = item.GetLostPowerStatus(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 4 Then '库门报警功能
                            ctl.value = item.GetDoorAlarmStatus(ctl.ici.Refid)
                        End If
                    End If
                End If
            Next
        Next
    End Sub

    Private Delegate Sub SetReadErrorLableVisibleHandler(ByVal bVisible As Boolean)

    ''' <summary>
    ''' 设置“读取数据失败”标签是否可见
    ''' </summary>
    ''' <param name="bVisible"></param>
    ''' <remarks></remarks>
    Private Sub SetReadErrorLableVisible(ByVal bVisible As Boolean)
        If Me.InvokeRequired Then
            Try
                Dim d As New SetReadErrorLableVisibleHandler(AddressOf _setReadErrorLableVisible)
                Me.Invoke(d, New Object() {bVisible})
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try

        Else
            _setReadErrorLableVisible(bVisible)
        End If
    End Sub

    ''' <summary>
    ''' 设置“读取数据失败”标签是否可见
    ''' </summary>
    ''' <param name="bVisible"></param>
    ''' <remarks></remarks>
    Private Sub _setReadErrorLableVisible(ByVal bVisible As Boolean)
        For Each page As TabPage In Me.TabControlImages.TabPages
            For Each ctl As Control In page.Controls
                If ctl.GetType().ToString() = GetType(Label).ToString() Then
                    ctl.Visible = bVisible
                End If
            Next
        Next
    End Sub


    ''' <summary>
    ''' 刷新工程数据显示控件的位置
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RefreshControls()
        If _bLoad Then
            For Each page As TabPage In Me.TabControlImages.TabPages
                For Each ctl As Control In page.Controls
                    If ctl.GetType IsNot GetType(PictureBox) AndAlso ctl.GetType IsNot GetType(Label) Then
                        Dim iWidth As Integer = page.Width
                        Dim iHeight As Integer = page.Height

                        Dim item As ImgControlItem = CType(ctl, ImgControl).ici
                        '( X / 1024.0) * iWidth为相对位置（百分比位置）
                        ctl.Location = New Point((item.cLeft / 1024.0) * iWidth, (item.cTop / 768.0) * iHeight)
                        'ctl.Size = New Size((item.cWidth / 1024.0) * iWidth, (item.cHeight / 768.0) * iHeight)
                        ctl.Size = New Size(item.cWidth, item.cHeight)
                    End If
                Next
            Next
        End If
    End Sub

    Private Sub TabControlImages_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControlImages.SizeChanged
        '刷新工程数据显示控件的位置
        RefreshControls()
    End Sub

    Private Sub TabControlImages_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControlImages.SelectedIndexChanged
        '刷新工程数据显示控件的位置
        RefreshControls()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.Timer1.Enabled = False
        StartNewdataRefresh()


        _bLoad = True
        Me.Visible = True
        RefreshControls()
    End Sub

    ''' <summary>
    ''' 窗体关闭时,停止数据的刷新
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        If _p IsNot Nothing Then
            _p.StopDataTransfer()
        End If

        MyBase.OnClosing(e)
    End Sub

End Class